using UnityEngine;
using UnityEngine.UI;

namespace FutureCorePlugin
{
    public class UIBGAdaptive : MonoBehaviour
    {
        private RectTransform rectTF;
        private Image image;

        private void Awake()
        {
            rectTF = GetComponent<RectTransform>();
            image = GetComponent<Image>();
            Adaptive();
        }

#if UNITY_EDITOR
        private float currScreenHeight;
        private float currScreenWidth;

        private void Update()
        {
            if (currScreenHeight != Screen.height || currScreenWidth != Screen.width)
            {
                currScreenHeight = Screen.height;
                currScreenWidth = Screen.width;
                AdaptiveConst.CurrAspectRatio = (float)Screen.height / Screen.width;
                Adaptive();
            }
        }
#endif

        private void Adaptive()
        {
            if (image == null || image.type != Image.Type.Simple) return;

            rectTF.anchoredPosition = Vector2.zero;
            rectTF.localScale = Vector3.one;
            image.SetNativeSize();
            float imageHeight = rectTF.sizeDelta.y;
            float imageWidth = rectTF.sizeDelta.x;

            float standardHeight = AdaptiveConst.StandardResolution.y;
            float standardWidth = AdaptiveConst.StandardResolution.x;
            float currHeight = Screen.height;
            float currWidth = Screen.width;

            float standardAspectRatio = AdaptiveConst.StandardAspectRatio;
            float currAspectRatio = AdaptiveConst.CurrAspectRatio;
            float imageExtendRatio = 0f;
            float scale = 0f;

            if (currAspectRatio > standardAspectRatio)
            {
                imageExtendRatio = imageHeight / standardHeight;
                scale = currAspectRatio / standardAspectRatio;
            }
            else
            {
                imageExtendRatio = imageWidth / standardWidth;
                scale = standardAspectRatio / currAspectRatio;
            }

            if (imageExtendRatio < scale)
            {
                scale /= imageExtendRatio;
                rectTF.localScale *= scale;
            }
        }
    }
}